package com.example.xinyun.init;

import com.example.xinyun.db.dbPsychological;
import com.example.xinyun.db.xinliList;
import com.example.xinyun.provider.PsychologicalProvider;
import com.google.gson.Gson;
import com.zzrv5.mylibrary.ZZRCallBack;
import com.zzrv5.mylibrary.ZZRHttp;
import ohos.aafwk.ability.AbilitySlice;
import ohos.agp.components.ListContainer;
import ohos.agp.window.dialog.ToastDialog;
import ohos.app.Context;

import java.util.ArrayList;
import java.util.List;


public class InitPsychological {
    private List<xinliList> xinliLists=new ArrayList();
    private PsychologicalProvider psychologicalProvider;
    public List<xinliList> getXinliLists() {
        return xinliLists;
    }

    //进行http请求并刷新listContainer
    public void Refresh(String url,Context context, AbilitySlice abilitySlice, ListContainer listContainer){
        //进行http访问
        ZZRHttp.get(url, new ZZRCallBack.CallBackString() {

            @Override
            //http访问出错，此部分在主线程中工作,可以更新UI等操做。
            public void onFailure(int code, String errorMessage) {
                new ToastDialog(context)
                        .setText("加载失败，请检查网络连接！")
                        .show();
            }
            @Override
            //http访问成功，此部分在主线程中工作，可以更新UI等操作。
            public  void onResponse(String response) {
                //将http请求返回的json字符串转换成一个dbPsychological类的对象
                dbPsychological dbPsychological=new Gson().fromJson(response, dbPsychological.class);
                if (dbPsychological!=null)
                {
                    List<xinliList> data = dbPsychological.getData();
                    //清空xinliLists中的数据
                    xinliLists.clear();
                    //将获取到的数据全部添加到xinliLists里面
                    xinliLists.addAll(data);
                    //对newsProvider进行更新
                    psychologicalProvider=new PsychologicalProvider(xinliLists, (AbilitySlice) abilitySlice);
                    listContainer.setItemProvider(psychologicalProvider);
                }
            }
        });
    }
    public void updata(String url,String json,Context context){
        ZZRHttp.postJson(url, json, new ZZRCallBack.CallBackString() {
            @Override
            public void onFailure(int i, String s) {
                new ToastDialog(context)
                        .setText("数据更新失败，请检查网络连接！")
                        .show();
            }

            @Override
            public void onResponse(String s) {
                xinliList xinliList=new xinliList();
                xinliList.setNumberCanyu(xinliList.getNumberCanyu()+1);
            }
        });
    }
}
